package org.advanced.aqs;

import org.advanced.security.Atomised;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author John.zhang
 * @version Id: ReentrantLocks, v 1.0 2020/12/10 11:22 ZhiYong Exp $
 */
public class ReentrantLocks {

    /**
     * 重入锁
     */
    static ReentrantLock lock = new ReentrantLock();

    public static int count = 0;

    public static void inc() {
        try {
            lock.lock();
            Thread.sleep(1);
            dear();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
        //这里的count实际经历三个指令 --javap -v Atomised.class (getstatic/iadd/putstatic)
        count++;//(实际只会一个线程来执行)
    }

    public static void dear() {
        lock.lock();//会争抢锁(正常的锁会导致死锁，重入锁解决这个问题，只记录锁次数)

        count--;

        lock.unlock();
        count++;
    }



    public static void main(String[] args) {
        int max = 100;
        for (int i = 0; i < max; i++) {
            new Thread(Atomised::inc).start();
        }
        try {
            Thread.sleep(4000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(count);
    }

}
